using System.Collections.Generic;
using System.Linq;
using System.Text;
using LDNS.SDK.Commands;
using LDNS.SDK.Commands.Models;
using LDNS.Utilities;

namespace LDNS.Commands
{
    /// <summary>
    /// 列出上游DNS服务器命令处理器
    /// 处理LIST_UPSTREAM命令，获取上游DNS服务器列表
    /// 作者：huobing
    /// </summary>
    public class ListUpstreamCommandHandler : CommandHandlerBase<ListUpstreamCommand, ListUpstreamResult>
    {
        /// <summary>
        /// 命令名称
        /// </summary>
        public override string CommandName => ListUpstreamCommand.NAME;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="upstreamDnsManager">上游DNS管理器实例</param>
        public ListUpstreamCommandHandler()
        {
        }

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args">命令参数</param>
        /// <returns>命令执行结果</returns>
        public override BaseCommandResult Execute(string[] args)
        {
            try
            {
                var command = new ListUpstreamCommand();
                if (!command.Validate(args, out string error))
                {
                    return BaseCommandResult.CreateErrorResult<ListUpstreamResult>(error, ListUpstreamCommand.NAME);
                }

                // 获取上游DNS服务器列表
                var upstreamServers = UpstreamDnsManager.Instance.UpstreamServers;
                // 获取域名映射配置
                var domainMappings = UpstreamDomainManager.Instance.GetDomainMap();
                
                // 创建结果对象
                var result = new ListUpstreamResult
                {
                    Success = true,
                    CommandName = ListUpstreamCommand.NAME,
                    Message = string.Empty
                };
                
                // 直接使用ListUpstreamCommand.cs中定义的ListUpstreamResult类型
                // 先添加域名映射信息，这是我们特别需要显示的
                foreach (var mapping in domainMappings)
                {
                    result.UpstreamServers.Add(new UpstreamServerInfo
                    {
                        Address = mapping.Key,
                        CacheCount = 0,
                        MainDomain = mapping.Value,
                        IsDefault = false
                    });
                }
                
                // 再添加上游服务器信息（如果还没有添加过）
                foreach (var server in upstreamServers)
                {
                    if (!result.UpstreamServers.Any(s => s.Address == server))
                    {
                        result.UpstreamServers.Add(new UpstreamServerInfo
                        {
                            Address = server,
                            CacheCount = 0,
                            MainDomain = null,
                            IsDefault = false
                        });
                    }
                }
                
                return result;
            }
            catch (Exception ex)
            {
                return BaseCommandResult.CreateErrorResult<ListUpstreamResult>($"列出上游DNS服务器失败: {ex.Message}", ListUpstreamCommand.NAME);
            }
        }
    }
}